package com.hqbzl.c1.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TestSemapHore {
    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    // 占一个位置
                    semaphore.acquire();
                    /*
                    final boolean acquire = semaphore.tryAcquire();
                    if (acquire) {
                        log.debug("thread running==========>");
                    } else {
                        log.debug("thread running wait");
                    }
                    */
                    log.debug("thread running==========>");
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 返还
                    semaphore.release();
                }
            }, "th-" + i).start();
        }

//        try {
//            System.out.println("the end 1");
//            semaphore.acquire(3);
//            System.out.println("semaphore.availablePermits() = " + semaphore.availablePermits());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println("the end 1");

    }
}
